import cv2
import os
import numpy as np


def slice_image_keep_center(image_path, output_dir, window_size=640, step_size=640):
    """
    对图片进行切片，只保留中间部分的切片，丢弃靠近边缘的切片。
    :param image_path: 输入图片路径
    :param output_dir: 切片保存路径
    :param window_size: 切片大小，默认 640x640
    :param step_size: 滑动步长，默认 640
    """
    # 读取大图片
    image = cv2.imread(image_path)
    h, w, _ = image.shape  # 高度、宽度和通道数

    # 确保输出目录存在
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 初始化切片计数器
    count = 0

    # 使用滑动窗口遍历图片
    for y in range(0, h - window_size + 1, step_size):
        for x in range(0, w - window_size + 1, step_size):
            # 跳过靠近边缘的切片
            if x == 0 or y == 0 or x + window_size >= w or y + window_size >= h:
                continue

            # 提取中间部分的切片
            slice_img = image[y:y + window_size, x:x + window_size]

            # 保存切片
            slice_filename = os.path.join(output_dir, f"slice_{count}.png")
            cv2.imwrite(slice_filename, slice_img)
            print(f"Saved {slice_filename}")
            count += 1


# 使用函数进行切片
image_path = 'black_template.jpg'  # 输入大图片路径
output_dir = 'rawB'  # 切片保存路径
slice_image_keep_center(image_path, output_dir, window_size=640, step_size=640)
